#include "teacherwindow.h"
#include "screenrecorder.h"
#include "networkstreamer.h"
#include "remotecontroller.h"
#include "screenviewer.h"
#include <QDebug>
#include <QApplication>
#include <QScreen>
#include <QMessageBox>
#include <QRegularExpression>
#include <QMouseEvent>

TeacherWindow::TeacherWindow(QWidget *parent) : QMainWindow(parent),
    screenRecorder(nullptr), networkStreamer(nullptr), remoteController(nullptr), screenViewer(nullptr),
    isStreaming(false), isRecording(false), isRemoteControlEnabled(false), isViewingStudentScreen(false)
{
    setupUI();
    
    // 设置窗口属性
    setWindowTitle("电子教室 - 教师端");
    setMinimumSize(1200, 900);  // 增大窗口最小尺寸
    resize(1400, 1000);         // 设置默认窗口大小
    
    // 获取屏幕尺寸
    QScreen *screen = QApplication::primaryScreen();
    QSize screenSize = screen->size();
    
    // 初始化核心模块
    screenRecorder = new ScreenRecorder(this);
    networkStreamer = new NetworkStreamer(this);
    remoteController = new RemoteController(this);
    screenViewer = new ScreenViewer(this);
    
    // 设置参数
    screenRecorder->setResolution(screenSize);
    screenRecorder->setFrameRate(15);
    screenRecorder->setBitrate(1000000);
    screenRecorder->setRecordingMode(ScreenRecorder::StreamOnly); // 默认仅推流
    
    // 设置远程控制参数
    remoteController->setSourceScreenSize(screenSize);
    remoteController->setTargetScreenSize(screenSize); // 假设目标屏幕尺寸相同
    remoteController->setTargetAddress("127.0.0.1", 5007); // 改为5007避免与ffplay冲突
    
    // 初始化模块
    screenRecorder->initialize();
    networkStreamer->initialize();
    remoteController->initialize();
    screenViewer->initialize();
    
    // 在对象创建后再连接信号
    setupConnections();
    
    // 初始化UI状态
    updateRecordingControls();
}

TeacherWindow::~TeacherWindow()
{
    if (isStreaming) {
        stopStreaming();
    }
    if (isRecording) {
        stopRecording();
    }
}

void TeacherWindow::setupUI()
{
    centralWidget = new QWidget(this);
    setCentralWidget(centralWidget);
    
    mainLayout = new QVBoxLayout(centralWidget);
    
    // 推流控制组
    streamingGroup = new QGroupBox("推流控制", this);
    QVBoxLayout* streamingLayout = new QVBoxLayout(streamingGroup);
    
    QHBoxLayout* streamingButtonLayout = new QHBoxLayout();
    startButton = new QPushButton("开始推流", this);
    stopButton = new QPushButton("停止推流", this);
    stopButton->setEnabled(false);
    
    streamingButtonLayout->addWidget(startButton);
    streamingButtonLayout->addWidget(stopButton);
    
    streamingStatusLabel = new QLabel("状态: 未推流", this);
    
    streamingLayout->addLayout(streamingButtonLayout);
    streamingLayout->addWidget(streamingStatusLabel);
    
    // 录屏控制组
    recordingGroup = new QGroupBox("录屏控制", this);
    QVBoxLayout* recordingLayout = new QVBoxLayout(recordingGroup);
    
    // 录制模式选择
    QHBoxLayout* modeLayout = new QHBoxLayout();
    QLabel* modeLabel = new QLabel("录制模式:", this);
    recordingModeCombo = new QComboBox(this);
    recordingModeCombo->addItem("仅推流", ScreenRecorder::StreamOnly);
    recordingModeCombo->addItem("仅录制文件", ScreenRecorder::FileOnly);
    recordingModeCombo->addItem("推流+录制", ScreenRecorder::StreamAndFile);
    
    modeLayout->addWidget(modeLabel);
    modeLayout->addWidget(recordingModeCombo);
    modeLayout->addStretch();
    
    // 录制控制按钮
    QHBoxLayout* recordingButtonLayout = new QHBoxLayout();
    startRecordingButton = new QPushButton("开始录制", this);
    stopRecordingButton = new QPushButton("停止录制", this);
    pauseRecordingButton = new QPushButton("暂停录制", this);
    
    stopRecordingButton->setEnabled(false);
    pauseRecordingButton->setEnabled(false);
    
    recordingButtonLayout->addWidget(startRecordingButton);
    recordingButtonLayout->addWidget(stopRecordingButton);
    recordingButtonLayout->addWidget(pauseRecordingButton);
    
    // 录制状态显示
    recordingStatusLabel = new QLabel("状态: 未录制", this);
    durationLabel = new QLabel("时长: 00:00:00", this);
    fileSizeLabel = new QLabel("文件大小: 0 MB", this);
    
    recordingProgressBar = new QProgressBar(this);
    recordingProgressBar->setVisible(false);
    
    recordingLayout->addLayout(modeLayout);
    recordingLayout->addLayout(recordingButtonLayout);
    recordingLayout->addWidget(recordingStatusLabel);
    recordingLayout->addWidget(durationLabel);
    recordingLayout->addWidget(fileSizeLabel);
    recordingLayout->addWidget(recordingProgressBar);
    
    // 远程控制组
    remoteControlGroup = new QGroupBox("远程控制", this);
    QVBoxLayout* remoteControlLayout = new QVBoxLayout(remoteControlGroup);
    
    // IP配置区域
    QHBoxLayout* ipConfigLayout = new QHBoxLayout();
    QLabel* ipLabel = new QLabel("目标IP:", this);
    targetIPEdit = new QLineEdit("127.0.0.1", this);
    targetIPEdit->setPlaceholderText("输入学生端IP地址");
    
    QLabel* portLabel = new QLabel("端口:", this);
    targetPortSpinBox = new QSpinBox(this);
    targetPortSpinBox->setRange(1024, 65535);
    targetPortSpinBox->setValue(5007);
    
    applyIPButton = new QPushButton("应用设置", this);
    
    ipConfigLayout->addWidget(ipLabel);
    ipConfigLayout->addWidget(targetIPEdit);
    ipConfigLayout->addWidget(portLabel);
    ipConfigLayout->addWidget(targetPortSpinBox);
    ipConfigLayout->addWidget(applyIPButton);
    ipConfigLayout->addStretch();
    
    // 当前连接状态
    currentIPLabel = new QLabel("当前连接: 127.0.0.1:5007", this);
    currentIPLabel->setStyleSheet("color: blue; font-weight: bold;");
    
    // 远程控制按钮
    remoteControlButton = new QPushButton("启用远程控制", this);
    remoteControlStatusLabel = new QLabel("状态: 未启用", this);
    
    remoteControlLayout->addLayout(ipConfigLayout);
    remoteControlLayout->addWidget(currentIPLabel);
    remoteControlLayout->addWidget(remoteControlButton);
    remoteControlLayout->addWidget(remoteControlStatusLabel);
    
    // 屏幕查看组
    QGroupBox* screenViewGroup = new QGroupBox("学生屏幕查看", this);
    QVBoxLayout* screenViewLayout = new QVBoxLayout(screenViewGroup);
    
    // 设置屏幕显示组的大小策略
    screenViewGroup->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    
    // 学生屏幕显示区域
    studentScreenLabel = new QLabel(this);
    studentScreenLabel->setMinimumSize(1024, 768);  // 增大最小尺寸
    studentScreenLabel->setMaximumSize(1920, 1080); // 增大最大尺寸
    studentScreenLabel->setStyleSheet("QLabel { background-color: black; border: 2px solid gray; }");
    studentScreenLabel->setText("学生屏幕将在这里显示");
    studentScreenLabel->setAlignment(Qt::AlignCenter);
    
    // 启用鼠标事件 - 关键设置
    studentScreenLabel->setMouseTracking(true);
    studentScreenLabel->setFocusPolicy(Qt::StrongFocus);  // 允许获得焦点
    studentScreenLabel->setAttribute(Qt::WA_TransparentForMouseEvents, false);  // 确保鼠标事件不被透明化
    studentScreenLabel->installEventFilter(this);
    
    qDebug() << "学生屏幕标签设置完成，鼠标追踪:" << studentScreenLabel->hasMouseTracking();
    qDebug() << "焦点策略:" << studentScreenLabel->focusPolicy();
    qDebug() << "鼠标事件透明:" << studentScreenLabel->testAttribute(Qt::WA_TransparentForMouseEvents);
    
    // 屏幕查看控制按钮
    viewStudentScreenButton = new QPushButton("开始查看学生屏幕", this);
    screenViewStatusLabel = new QLabel("状态: 未查看", this);
    
    screenViewLayout->addWidget(studentScreenLabel);
    screenViewLayout->addWidget(viewStudentScreenButton);
    screenViewLayout->addWidget(screenViewStatusLabel);
    
    // 创建左右分栏布局
    QHBoxLayout* mainHorizontalLayout = new QHBoxLayout();
    
    // 左侧控制面板
    QVBoxLayout* leftPanelLayout = new QVBoxLayout();
    leftPanelLayout->addWidget(streamingGroup);
    leftPanelLayout->addWidget(recordingGroup);
    leftPanelLayout->addWidget(remoteControlGroup);
    leftPanelLayout->addStretch();
    
    // 右侧屏幕显示区域
    QVBoxLayout* rightPanelLayout = new QVBoxLayout();
    rightPanelLayout->addWidget(screenViewGroup);
    rightPanelLayout->addStretch();
    
    // 设置左右面板的比例 (1:3)
    mainHorizontalLayout->addLayout(leftPanelLayout, 1);
    mainHorizontalLayout->addLayout(rightPanelLayout, 3);
    
    mainLayout->addLayout(mainHorizontalLayout);
}

void TeacherWindow::setupConnections()
{
    // 推流控制信号连接
    connect(startButton, &QPushButton::clicked, this, &TeacherWindow::startStreaming);
    connect(stopButton, &QPushButton::clicked, this, &TeacherWindow::stopStreaming);
    
    // 录屏控制信号连接
    connect(startRecordingButton, &QPushButton::clicked, this, &TeacherWindow::startRecording);
    connect(stopRecordingButton, &QPushButton::clicked, this, &TeacherWindow::stopRecording);
    connect(pauseRecordingButton, &QPushButton::clicked, this, &TeacherWindow::togglePauseRecording);
    connect(recordingModeCombo, QOverload<int>::of(&QComboBox::currentIndexChanged), 
            this, &TeacherWindow::onRecordingModeChanged);
    
    // 远程控制信号连接
    connect(remoteControlButton, &QPushButton::clicked, this, &TeacherWindow::toggleRemoteControl);
    connect(applyIPButton, &QPushButton::clicked, this, &TeacherWindow::applyIPSettings);
    
    // 屏幕查看信号连接
    connect(viewStudentScreenButton, &QPushButton::clicked, this, &TeacherWindow::toggleViewStudentScreen);
    
    // 远程控制状态信号连接
    connect(remoteController, &RemoteController::enabled, this, &TeacherWindow::onRemoteControlEnabled);
    connect(remoteController, &RemoteController::disabled, this, &TeacherWindow::onRemoteControlDisabled);
    connect(remoteController, &RemoteController::eventCaptured, this, &TeacherWindow::onRemoteControlEventCaptured);
    connect(remoteController, &RemoteController::commandSent, this, &TeacherWindow::onRemoteControlCommandSent);
    connect(remoteController, &RemoteController::errorOccurred, this, &TeacherWindow::onRemoteControlError);
    
    // 录屏状态信号连接
    connect(screenRecorder, &ScreenRecorder::recordingStarted, [this]() {
        isRecording = true;
        updateRecordingControls();
    });
    
    connect(screenRecorder, &ScreenRecorder::recordingStopped, [this]() {
        isRecording = false;
        updateRecordingControls();
    });
    
    connect(screenRecorder, &ScreenRecorder::recordingPaused, [this]() {
        updateRecordingControls();
    });
    
    connect(screenRecorder, &ScreenRecorder::recordingResumed, [this]() {
        updateRecordingControls();
    });
    
    connect(screenRecorder, &ScreenRecorder::statusChanged, 
            this, &TeacherWindow::onRecordingStatusChanged);
    connect(screenRecorder, &ScreenRecorder::durationChanged, 
            this, &TeacherWindow::onRecordingDurationChanged);
    connect(screenRecorder, &ScreenRecorder::fileSizeChanged, 
            this, &TeacherWindow::onFileSizeChanged);
    connect(screenRecorder, &ScreenRecorder::errorOccurred, 
            this, &TeacherWindow::onRecordingError);
    
    // 屏幕查看状态信号连接
    connect(screenViewer, &ScreenViewer::listeningStarted, this, &TeacherWindow::onScreenViewStarted);
    connect(screenViewer, &ScreenViewer::listeningStopped, this, &TeacherWindow::onScreenViewStopped);
    connect(screenViewer, &ScreenViewer::screenReceived, this, &TeacherWindow::onScreenReceived);
    connect(screenViewer, &ScreenViewer::errorOccurred, this, &TeacherWindow::onScreenViewError);
}

void TeacherWindow::startStreaming()
{
    if (isStreaming) return;
    
    qDebug() << "开始推流...";
    
    if (screenRecorder->startRecording()) {
        isStreaming = true;
        startButton->setEnabled(false);
        stopButton->setEnabled(true);
        streamingStatusLabel->setText("状态: 推流中");
        qDebug() << "推流启动成功";
    } else {
        qDebug() << "推流启动失败";
        QMessageBox::warning(this, "推流失败", "无法启动推流，请检查配置");
    }
}

void TeacherWindow::stopStreaming()
{
    if (!isStreaming) return;
    
    qDebug() << "停止推流...";
    
    screenRecorder->stopRecording();
    
    isStreaming = false;
    startButton->setEnabled(true);
    stopButton->setEnabled(false);
    streamingStatusLabel->setText("状态: 未推流");
    
    qDebug() << "推流已停止";
}

void TeacherWindow::startRecording()
{
    if (isRecording) return;
    
    qDebug() << "开始录制...";
    
    if (screenRecorder->startRecording()) {
        isRecording = true;
        updateRecordingControls();
        qDebug() << "录制启动成功";
    } else {
        qDebug() << "录制启动失败";
        QMessageBox::warning(this, "录制失败", "无法启动录制，请检查配置");
    }
}

void TeacherWindow::stopRecording()
{
    if (!isRecording) return;
    
    qDebug() << "停止录制...";
    
    screenRecorder->stopRecording();
    
    isRecording = false;
    updateRecordingControls();
    
    qDebug() << "录制已停止";
}

void TeacherWindow::togglePauseRecording()
{
    if (!isRecording) return;
    
    if (screenRecorder->isPaused()) {
        // 当前是暂停状态，恢复录制
        screenRecorder->resumeRecording();
        qDebug() << "恢复录制";
    } else {
        // 当前是录制状态，暂停录制
        screenRecorder->pauseRecording();
        qDebug() << "暂停录制";
    }
    
    updateRecordingControls();
}



void TeacherWindow::onRecordingModeChanged(int index)
{
    ScreenRecorder::RecordingMode mode = static_cast<ScreenRecorder::RecordingMode>(
        recordingModeCombo->itemData(index).toInt());
    
    screenRecorder->setRecordingMode(mode);
    qDebug() << "录制模式已更改为:" << mode;
}

void TeacherWindow::applyIPSettings()
{
    QString newIP = targetIPEdit->text().trimmed();
    quint16 newPort = static_cast<quint16>(targetPortSpinBox->value());
    
    // 简单的IP地址验证
    QRegularExpression ipRegex("^(\\d{1,3}\\.){3}\\d{1,3}$");
    if (!ipRegex.match(newIP).hasMatch()) {
        QMessageBox::warning(this, "IP地址错误", "请输入有效的IP地址格式，例如：192.168.1.100");
        return;
    }
    
    // 更新远程控制器设置
    remoteController->setTargetAddress(newIP, newPort);
    
    // 更新显示
    currentIPLabel->setText(QString("当前连接: %1:%2").arg(newIP).arg(newPort));
    currentIPLabel->setStyleSheet("color: green; font-weight: bold;");
    
    qDebug() << "远程控制目标地址已更新为:" << newIP << ":" << newPort;
    
    QMessageBox::information(this, "设置成功", 
        QString("远程控制目标地址已更新为:\n%1:%2\n\n请确保学生端已启动并监听该端口").arg(newIP).arg(newPort));
}

void TeacherWindow::toggleRemoteControl()
{
    if (isRemoteControlEnabled) {
        remoteController->disable();
        remoteControlButton->setText("启用远程控制");
        remoteControlStatusLabel->setText("状态: 未启用");
        isRemoteControlEnabled = false;
    } else {
        remoteController->enable();
        remoteControlButton->setText("禁用远程控制");
        remoteControlStatusLabel->setText("状态: 已启用");
        isRemoteControlEnabled = true;
    }
}

void TeacherWindow::updateRecordingControls()
{
    bool recording = screenRecorder->isRecording();
    bool paused = screenRecorder->isPaused();
    
    startRecordingButton->setEnabled(!recording);
    stopRecordingButton->setEnabled(recording);
    pauseRecordingButton->setEnabled(recording); // 录制时始终可以点击暂停/恢复按钮
    
    if (paused) {
        pauseRecordingButton->setText("恢复录制");
    } else {
        pauseRecordingButton->setText("暂停录制");
    }
}

void TeacherWindow::onRecordingStatusChanged(const QString& status)
{
    recordingStatusLabel->setText("状态: " + status);
}

void TeacherWindow::onRecordingDurationChanged(qint64 duration)
{
    durationLabel->setText("时长: " + formatDuration(duration));
}

void TeacherWindow::onFileSizeChanged(qint64 size)
{
    fileSizeLabel->setText("文件大小: " + formatFileSize(size));
}

void TeacherWindow::onRecordingError(const QString& error)
{
    QMessageBox::warning(this, "录制错误", "录制过程中发生错误: " + error);
}

// 远程控制相关槽函数实现
void TeacherWindow::onRemoteControlEnabled()
{
    remoteControlButton->setText("禁用远程控制");
    remoteControlStatusLabel->setText("状态: 已启用");
    isRemoteControlEnabled = true;
    qDebug() << "远程控制已启用";
}

void TeacherWindow::onRemoteControlDisabled()
{
    remoteControlButton->setText("启用远程控制");
    remoteControlStatusLabel->setText("状态: 未启用");
    isRemoteControlEnabled = false;
    qDebug() << "远程控制已禁用";
}

void TeacherWindow::onRemoteControlEventCaptured(const QString& eventInfo)
{
    qDebug() << "远程控制事件捕获:" << eventInfo;
}

void TeacherWindow::onRemoteControlCommandSent(const QString& commandInfo)
{
    qDebug() << "远程控制命令发送:" << commandInfo;
}

void TeacherWindow::onRemoteControlError(const QString& error)
{
    QMessageBox::warning(this, "远程控制错误", "远程控制过程中发生错误: " + error);
}

// 屏幕查看相关槽函数实现
void TeacherWindow::toggleViewStudentScreen()
{
    if (isViewingStudentScreen) {
        screenViewer->stopListening();
        viewStudentScreenButton->setText("开始查看学生屏幕");
        isViewingStudentScreen = false;
    } else {
        screenViewer->setDisplayLabel(studentScreenLabel);
        screenViewer->startListening(5006);
        viewStudentScreenButton->setText("停止查看学生屏幕");
        isViewingStudentScreen = true;
    }
}

void TeacherWindow::onScreenViewStarted()
{
    screenViewStatusLabel->setText("状态: 正在查看");
    qDebug() << "开始查看学生屏幕";
}

void TeacherWindow::onScreenViewStopped()
{
    screenViewStatusLabel->setText("状态: 未查看");
    studentScreenLabel->setText("学生屏幕将在这里显示");
    qDebug() << "停止查看学生屏幕";
}

void TeacherWindow::onScreenReceived(const QPixmap& screen)
{
    // 更新学生端实际屏幕尺寸
    studentScreenSize = screen.size();
    
    // 更新显示区域尺寸
    displayScreenSize = studentScreenLabel->size();
    
    qDebug() << "接收到学生屏幕图像，尺寸:" << studentScreenSize 
             << "显示区域尺寸:" << displayScreenSize;
}

void TeacherWindow::onScreenViewError(const QString& error)
{
    screenViewStatusLabel->setText("状态: 查看错误");
    qDebug() << "屏幕查看错误:" << error;
}

// 事件过滤器实现
bool TeacherWindow::eventFilter(QObject* obj, QEvent* event)
{
    if (obj == studentScreenLabel) {
        // 只处理鼠标相关事件，忽略其他系统事件
        switch (event->type()) {
            case QEvent::MouseButtonPress:
            case QEvent::MouseButtonRelease:
            case QEvent::MouseMove:
            case QEvent::Enter:
            case QEvent::Leave: {
                // 只有在启用远程控制且查看学生屏幕时才输出调试信息
                if (isViewingStudentScreen && isRemoteControlEnabled) {
                    qDebug() << "=== 事件过滤器 ===";
                    qDebug() << "事件类型:" << event->type();
                    qDebug() << "isViewingStudentScreen:" << isViewingStudentScreen;
                    qDebug() << "isRemoteControlEnabled:" << isRemoteControlEnabled;
                    
                    switch (event->type()) {
                        case QEvent::MouseButtonPress: {
                            qDebug() << "*** 处理鼠标按下事件 ***";
                            QMouseEvent* mouseEvent = static_cast<QMouseEvent*>(event);
                            onStudentScreenPressed(mouseEvent);
                            return true;
                        }
                        case QEvent::MouseButtonRelease: {
                            qDebug() << "*** 处理鼠标释放事件 ***";
                            QMouseEvent* mouseEvent = static_cast<QMouseEvent*>(event);
                            onStudentScreenReleased(mouseEvent);
                            return true;
                        }
                        case QEvent::MouseMove: {
                            qDebug() << "*** 处理鼠标移动事件 ***";
                            QMouseEvent* mouseEvent = static_cast<QMouseEvent*>(event);
                            onStudentScreenMoved(mouseEvent);
                            return true;
                        }
                        case QEvent::Enter: {
                            qDebug() << "鼠标进入学生屏幕区域";
                            break;
                        }
                        case QEvent::Leave: {
                            qDebug() << "鼠标离开学生屏幕区域";
                            break;
                        }
                        default:
                            // 处理其他鼠标相关事件（如MouseButtonDblclick等）
                            break;
                    }
                } else {
                    // 只在鼠标进入/离开时输出一次提示
                    if (event->type() == QEvent::Enter) {
                        qDebug() << "鼠标进入学生屏幕区域 (远程控制未启用)";
                    } else if (event->type() == QEvent::Leave) {
                        qDebug() << "鼠标离开学生屏幕区域";
                    }
                }
                break;
            }
            case QEvent::Paint:
            case QEvent::Show:
            case QEvent::Hide:
            case QEvent::Move:
            case QEvent::Resize:
            case QEvent::WindowActivate:
            case QEvent::WindowDeactivate:
            case QEvent::FocusIn:
            case QEvent::FocusOut:
            case QEvent::KeyPress:
            case QEvent::KeyRelease:
            case QEvent::Timer:
            case QEvent::None:
            case QEvent::Create:
            case QEvent::Destroy:
            case QEvent::Close:
            case QEvent::Quit:
            case QEvent::ParentChange:
            case QEvent::MouseButtonDblClick:
            case QEvent::FocusAboutToChange:
            default:
                // 忽略所有其他事件类型
                break;
        }
    }
    return QMainWindow::eventFilter(obj, event);
}

// 坐标转换函数
QPoint TeacherWindow::convertDisplayToStudentCoordinates(const QPoint& displayPos)
{
    qDebug() << "=== 坐标转换 ===";
    qDebug() << "输入显示坐标:" << displayPos;
    qDebug() << "学生屏幕尺寸:" << studentScreenSize;
    qDebug() << "显示区域尺寸:" << displayScreenSize;
    
    if (studentScreenSize.isEmpty() || displayScreenSize.isEmpty()) {
        qDebug() << "尺寸为空，返回原坐标";
        return displayPos;
    }
    
    // 计算缩放比例
    double scaleX = static_cast<double>(studentScreenSize.width()) / displayScreenSize.width();
    double scaleY = static_cast<double>(studentScreenSize.height()) / displayScreenSize.height();
    
    qDebug() << "缩放比例 X:" << scaleX << "Y:" << scaleY;
    
    // 转换坐标
    int studentX = static_cast<int>(displayPos.x() * scaleX);
    int studentY = static_cast<int>(displayPos.y() * scaleY);
    
    QPoint result(studentX, studentY);
    qDebug() << "转换后坐标:" << result;
    qDebug() << "=== 坐标转换完成 ===";
    
    return result;
}

// 屏幕控制相关槽函数实现
void TeacherWindow::onStudentScreenPressed(QMouseEvent* event)
{
    if (!isRemoteControlEnabled) {
        qDebug() << "远程控制未启用，忽略鼠标事件";
        return;
    }
    
    if (!isViewingStudentScreen) {
        qDebug() << "未查看学生屏幕，忽略鼠标事件";
        return;
    }
    
    QPoint displayPos = event->pos();
    QPoint studentPos = convertDisplayToStudentCoordinates(displayPos);
    
    qDebug() << "=== 鼠标按下事件 ===";
    qDebug() << "显示坐标:" << displayPos;
    qDebug() << "学生坐标:" << studentPos;
    qDebug() << "学生屏幕尺寸:" << studentScreenSize;
    qDebug() << "显示区域尺寸:" << displayScreenSize;
    qDebug() << "鼠标按钮:" << event->button();
    
    // 发送鼠标按下命令到学生端
    QJsonObject mouseEvent = remoteController->createMouseEvent(
        QEvent::MouseButtonPress, 
        studentPos, 
        event->button()
    );
    
    qDebug() << "发送的JSON命令:" << QJsonDocument(mouseEvent).toJson();
    remoteController->sendCommand(mouseEvent);
    
    qDebug() << "=== 鼠标按下事件处理完成 ===";
}

void TeacherWindow::onStudentScreenReleased(QMouseEvent* event)
{
    if (!isRemoteControlEnabled) return;
    
    QPoint studentPos = convertDisplayToStudentCoordinates(event->pos());
    qDebug() << "学生屏幕释放:" << event->pos() << "->" << studentPos;
    
    // 发送鼠标释放命令到学生端
    QJsonObject mouseEvent = remoteController->createMouseEvent(
        QEvent::MouseButtonRelease, 
        studentPos, 
        event->button()
    );
    remoteController->sendCommand(mouseEvent);
}

void TeacherWindow::onStudentScreenMoved(QMouseEvent* event)
{
    if (!isRemoteControlEnabled) return;
    
    QPoint studentPos = convertDisplayToStudentCoordinates(event->pos());
    qDebug() << "学生屏幕移动:" << event->pos() << "->" << studentPos;
    
    // 发送鼠标移动命令到学生端
    QJsonObject mouseEvent = remoteController->createMouseEvent(
        QEvent::MouseMove, 
        studentPos, 
        Qt::NoButton
    );
    remoteController->sendCommand(mouseEvent);
}

QString TeacherWindow::formatDuration(qint64 msecs)
{
    int hours = msecs / (1000 * 60 * 60);
    int minutes = (msecs % (1000 * 60 * 60)) / (1000 * 60);
    int seconds = (msecs % (1000 * 60)) / 1000;
    
    return QString("%1:%2:%3")
        .arg(hours, 2, 10, QChar('0'))
        .arg(minutes, 2, 10, QChar('0'))
        .arg(seconds, 2, 10, QChar('0'));
}

QString TeacherWindow::formatFileSize(qint64 bytes)
{
    if (bytes < 1024) {
        return QString("%1 B").arg(bytes);
    } else if (bytes < 1024 * 1024) {
        return QString("%1 KB").arg(bytes / 1024.0, 0, 'f', 1);
    } else if (bytes < 1024 * 1024 * 1024) {
        return QString("%1 MB").arg(bytes / (1024.0 * 1024.0), 0, 'f', 1);
    } else {
        return QString("%1 GB").arg(bytes / (1024.0 * 1024.0 * 1024.0), 0, 'f', 1);
    }
}
